package sz.com.postoffice.jxyzwgcase.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.sun.istack.NotNull;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sz.com.postoffice.jxyzwgcase.constants.Constants;
import sz.com.postoffice.jxyzwgcase.core.TableDataInfo;
import sz.com.postoffice.jxyzwgcase.pojo.DailyIncome;
import sz.com.postoffice.jxyzwgcase.pojo.DailyIncomeSummary;
import sz.com.postoffice.jxyzwgcase.pojo.DailyIncomeSummaryList;
import sz.com.postoffice.jxyzwgcase.pojo.UserAdo;
import sz.com.postoffice.jxyzwgcase.service.DailyIncomeSummaryService;
import sz.com.postoffice.jxyzwgcase.service.UserAdoService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Api(value = "日收入汇总表", tags = "{日收入汇总表API}")
@RestController
@Slf4j
@RequestMapping(value = "/income")
public class DailyIncomeSummaryController {
    @Resource
    private DailyIncomeSummaryService dailyIncomeSummaryService;

    @Autowired
    private UserAdoService userAdoService;

    @ApiOperation(value = "查询日收入汇总日期列表", notes = "查询日收入汇总日期列表")
    @RequestMapping(value = "/summarys/date", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", dataType = "int", paramType = "path", required = true),
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "int", paramType = "path", required = true)
    })
    public TableDataInfo findByCodeAndDate(DailyIncomeSummaryList dailyIncomeSummaryList) {
        System.out.println("开始查询...");
        return dailyIncomeSummaryService.queryListPeriod(dailyIncomeSummaryList);
    }

    @ApiOperation(value = "查询日收入列表", notes = "查询日收入列表")
    @RequestMapping(value = "/summarys", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", dataType = "int", paramType = "path", required = true),
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "int", paramType = "path", required = true)
    })
    public TableDataInfo findByInfo(DailyIncomeSummary dailyIncomeSummary) {
        System.out.println("开始查询...");
        return dailyIncomeSummaryService.findByListEntity(dailyIncomeSummary);
    }

    @ApiOperation(value = "查询日收入汇总表详情", notes = "查询日收入汇总表详情")
    @RequestMapping(value = "/summarys/{id}", method = RequestMethod.GET)
    public DailyIncomeSummary findById(@PathVariable("id") @NotNull @ApiParam(name="日收入汇总id",value="path传入",required=true) Integer id) {
        System.out.println("开始查询...");
        return dailyIncomeSummaryService.findByPrimaryKey(id);
    }

    @ApiOperation(value = "新增日收入信息", notes = "新增日收入信息")
    @RequestMapping(value = "/dailyIncomes", method = RequestMethod.POST)
    public boolean insert(@RequestBody DailyIncome dailyIncome) {
        String adoId = dailyIncome.getAdoId();
        if (StringUtils.isNotEmpty(adoId)) {
            System.out.println("传入adoId: " + adoId);
            UserAdo searchAdo = getUserAdo(adoId);
            if (searchAdo != null) {
                System.out.print("adoId找到对应用户，userCode: " + searchAdo.getUserCode());
                System.out.println("userName: " + searchAdo.getUserName());
                dailyIncome.setUserCode(searchAdo.getUserCode());
                dailyIncome.setUserName(searchAdo.getUserName());
                dailyIncome.setDeptCode(searchAdo.getDeptCode());
            }
        }
        if (StringUtils.isEmpty(dailyIncome.getUserCode())) {
            return false;
        }
        System.out.println("app新增日报...");
        if(dailyIncome.getId() == null ||dailyIncome.getId() == 0) {
            return dailyIncomeSummaryService.insertSummaryByDaily(dailyIncome);
        } else {
            return dailyIncomeSummaryService.updateTodayIncome(dailyIncome);
        }
    }

    @ApiOperation(value = "修改当天日收入信息", notes = "修改当天日收入信息")
    @RequestMapping(value = "/dailyIncomes", method = RequestMethod.PUT)
    public boolean updateTodayIncome(@RequestBody DailyIncome dailyIncome) {
        System.out.println("开始修改...");
        return dailyIncomeSummaryService.updateTodayIncome(dailyIncome);
    }

    @ApiOperation(value = "修改历史日收入信息", notes = "修改历史日收入信息")
    @RequestMapping(value = "/dailyIncomes/history", method = RequestMethod.PUT)
    public boolean updateHistory(@RequestBody DailyIncome dailyIncome) {
        System.out.println("开始修改...");
        return dailyIncomeSummaryService.updateHistoryIncome(dailyIncome);
    }

    @ApiOperation(value = "日收入表 excel下载", notes = "日收入表 excel下载")
    @RequestMapping(value = "/summarys/download", method = RequestMethod.GET)
    public void download(HttpServletResponse response, DailyIncomeSummary dailyIncomeSummary) throws IOException {
        List<DailyIncomeSummary> list = dailyIncomeSummaryService.queryAll(dailyIncomeSummary);
        String title = "日收入汇总";
        if (StringUtils.isNotEmpty(dailyIncomeSummary.getStatDate())) {
            title = dailyIncomeSummary.getStatDate() + "-日收入汇总";
        }
        String fileName= title + ".xlsx";
        fileName = URLEncoder.encode(fileName, Constants.UTF8);
        response.addHeader("Content-Disposition", "filename=" + fileName);
        OutputStream outputStream = response.getOutputStream();

        EasyExcel.write(outputStream, DailyIncomeSummary.class).sheet(title).doWrite(list);
        outputStream.close();
    }

    @ApiOperation(value = "查询单日收入", notes = "查询日收入列表")
    @RequestMapping(value = "/summary/app", method = RequestMethod.GET)
    public TableDataInfo findDailyIncome(DailyIncomeSummary dailyIncomeSummary) {
        String adoId = dailyIncomeSummary.getAdoId();
        if (StringUtils.isNotEmpty(adoId)) {
            System.out.println("传入adoId: " + adoId);
            UserAdo searchAdo = getUserAdo(adoId);
            if (searchAdo == null) {
                return errorTable(400,"该用户信息未录入系统");
            }
            System.out.print("adoId找到对应用户，userCode: " + searchAdo.getUserCode());
            System.out.println("userName: " + searchAdo.getUserName());
            if (StringUtils.isEmpty(searchAdo.getUserCode())) {
                return errorTable(400,"该用户信息未录入系统");
            }
            dailyIncomeSummary.setUserCode(searchAdo.getUserCode());
        }
        System.out.println("开始查询...");
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(200);
        List<DailyIncomeSummary> list = new ArrayList<>();
        list.add(dailyIncomeSummaryService.getDailyIncomeByUser(dailyIncomeSummary));
        tableDataInfo.setRows(list);
        return tableDataInfo;
    }


    private UserAdo getUserAdo(String adoId) {
        UserAdo userAdo = new UserAdo();
        userAdo.setAdoId(adoId);
        return userAdoService.findByEntity(userAdo);
    }

    private TableDataInfo errorTable(int code, String msg) {
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(code);
        tableDataInfo.setMsg(msg);
        return tableDataInfo;
    }
}
